import { useMessage } from '@/hooks/web/useMessage';
import Stomp from 'stompjs';
import SockJS from 'sockjs-client/dist/sockjs.min.js';

// const hcWsUrl = import.meta.env.VITE_HC_HTTP;

let stompClient: Stomp.Client | undefined;
let websocket;

const { createMessage } = useMessage();

async function connect(): Promise<Stomp.Client> {
  // websocket = new SockJS(hcWsUrl + '/ws/push/sockjs/stomp'); //建立连接
  websocket = new SockJS('/ws/push/sockjs/stomp'); //建立连接
  websocket.onclose = () => {
    console.log('123 onclose');
  };
  // eslint-disable-next-line prefer-const
  stompClient = Stomp.over(websocket);
  stompClient.heartbeat.outgoing = 2000;
  stompClient.heartbeat.incoming = 2000;

  return await new Promise((resolve, reject) => {
    stompClient!.connect(
      {
        login: 'guest',
        passcode: 'guest',
      },
      function () {
        createMessage.info('ws连接成功');
        resolve(stompClient!);
      },
      function (e) {
        createMessage.error('ws失败' + e);
        reject(e);
      },
    );
  });
}

export async function getStompClient(): Promise<Stomp.Client> {
  if (stompClient && stompClient.connected) {
    return Promise.resolve(stompClient);
  }
  return connect();
}

export function disconnectWs() {
  if (stompClient && stompClient.connected) {
    console.log('stompClient && stompClient.connected');
  }
  stompClient?.disconnect(() => {
    console.log('i want stompClient disconnect');
  });
  // websocket.close();
  // console.log('i want websocket disconnect');
}
